<template>
  <div class="device-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备管理</span>
          <el-button type="primary" @click="fetchDevices">刷新</el-button>
        </div>
      </template>

      <el-table :data="deviceList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="device_id" label="ID" width="80" />
        <el-table-column prop="device_name" label="设备名称" />
        <el-table-column prop="device_type" label="设备类型" width="100">
          <template #default="scope">
            {{ getDeviceTypeText(scope.row.device_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="room_id" label="房间" width="80" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../components/utils/request'

const deviceList = ref([])
const loading = ref(false)

const deviceTypeMap = {
  1: '灯光',
  2: '空调',
  3: '门锁',
  4: '窗帘',
  5: '传感器'
}

onMounted(() => {
  fetchDevices()
})

const fetchDevices = async () => {
  loading.value = true
  try {
    const response = await request.get('/devices/findAll')
    if (response.code === 200) {
      deviceList.value = response.data || []
      ElMessage.success(`加载了 ${deviceList.value.length} 个设备`)
    } else {
      ElMessage.error('获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表错误:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除设备 "${row.device_name}" 吗？`,
      '确认删除',
      { type: 'warning' }
  ).then(async () => {
    try {
      const response = await request.delete(`/devices/delete/${row.device_id}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchDevices()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const getDeviceTypeText = (type) => {
  return deviceTypeMap[type] || '未知'
}
</script>

<style scoped>
.device-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>